package cn.itcast.itcaststore.utils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int height = 50;
        int width = 100;
        //1.在内存中创建图片
         BufferedImage  image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //2.美化图片

        //2.1获取画笔对象
        Graphics graphics = image.getGraphics();

        //设置颜色
        graphics.setColor(Color.PINK);
        //填充颜色
        graphics.fillRect(0,0,width,height);

        //画边框
        graphics.setColor(Color.BLUE);
        graphics.drawRect(0,0,width-1,height-1);

        //设置字符
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";

        //获取随机生成角标
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<4;i++){
            int count = r.nextInt(str.length());
            //获取角标内容
            char c = str.charAt(count);
            sb.append(c);
           //写验证码
            graphics.drawString(c+"",width/5*i,height/2);
        }
        //获取字符串
        String checkcode = sb.toString();
        //将字符串存入session
        HttpSession session = request.getSession();
        session.setAttribute("checkcode",checkcode);
        //
        graphics.setColor(Color.GREEN);
        for (int x= 0;x<10;x++){
              int r1 = r.nextInt(width);
              int r2 = r.nextInt(width);
              int h1 = r.nextInt(height);
              int h2 = r.nextInt(height);
             //画干扰线
              graphics.drawLine(r1,r2,h1,h2);
   }


        //3.将图片输出
        ImageIO.write(image,"jpg",response.getOutputStream());
    }


}
